package cn.com.lsy.product.lepao.service.impl;

import cn.com.lsy.product.lepao.common.Constant;
import cn.com.lsy.product.lepao.service.IJpushService;
import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class JpushService implements IJpushService {

    private Logger log = Logger.getLogger(JpushService.class);

    @Override
    public boolean pushMessage(List<String> phoneList, String message, String extra) {

        if (phoneList != null && phoneList.size() > 0) {

            for (String value : phoneList) {
                jpushSdk(value, message, 1, extra);
                jpushSdk(value, message, 2, extra);
            }
        } else {

            jpushSdk("", message, 0, extra);
        }


        return false;
    }


    private boolean jpushSdk(String phone, String content, int type, String extra) {

        boolean result = false;

        JPushClient jpushClient = new JPushClient(
                Constant.jpushConfig.masterSecret,
                Constant.jpushConfig.appKey, null,
                ClientConfig.getInstance());

        PushPayload payload = null;

        if (type == 0) {
            payload = buildPushObject_all_all_alert(content, extra);
        } else if (type == 1) {
            payload = buildPushObject_all_tag_alert(content, phone, extra);
        } else if (type == 2) {
            payload = buildPushObject_all_alias_alert(content, phone, extra);
        }

        log.info(payload);

        try {

            PushResult info = jpushClient.sendPush(payload);
            log.info(info);
            if (info.getResponseCode() == 200) {

                result = true;
            }
            log.info(result);

        } catch (APIConnectionException e) {
            e.printStackTrace();
            log.error("Connection error, should retry later", e);
        } catch (APIRequestException e) {
            e.printStackTrace();
            log.error("Should review the error, and fix the request", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
        }

        return result;
    }


    /**
     * 构造请求实例（推送全部）
     *
     * @param content
     * @return
     */
    public PushPayload buildPushObject_all_all_alert(String content, String extra) {

        PushPayload.Builder pushPayload = PushPayload.newBuilder();

        pushPayload.
                setPlatform(Platform.all()).
                setOptions(Options.newBuilder().setApnsProduction(true).build());

        if (StringUtils.isNotEmpty(extra)) {

            pushPayload.setNotification(Notification.newBuilder().
                    setAlert(content).
                    addPlatformNotification(AndroidNotification.newBuilder().addExtra("data", extra).build()).
                    addPlatformNotification(IosNotification.newBuilder().addExtra("data", extra).build()).build());

        } else {

            pushPayload.setNotification(Notification.alert(content));
        }

        pushPayload.setAudience(Audience.all());

        return pushPayload.build();
    }


    /**
     * 构造请求实例（推送tag）
     *
     * @param content
     * @param phone
     * @return
     */
    public PushPayload buildPushObject_all_tag_alert(String content, String phone, String extra) {

        PushPayload.Builder pushPayload = PushPayload.newBuilder();

        pushPayload.
                setPlatform(Platform.all()).
                setOptions(Options.newBuilder().setApnsProduction(true).build()).
                setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag(phone))
                        .build());

        if (StringUtils.isNotEmpty(extra)) {

            pushPayload.setNotification(Notification.newBuilder().
                    setAlert(content).
                    addPlatformNotification(AndroidNotification.newBuilder().addExtra("data", extra).build()).
                    addPlatformNotification(IosNotification.newBuilder().addExtra("data", extra).build()).build());

        } else {

            pushPayload.setNotification(Notification.alert(content));
        }

        return pushPayload.build();
    }


    /**
     * 构造请求实例（推送别名）
     *
     * @param content
     * @param phone
     * @return
     */
    public PushPayload buildPushObject_all_alias_alert(String content, String phone, String extra) {

        PushPayload.Builder pushPayload = PushPayload.newBuilder();

        pushPayload.
                setPlatform(Platform.all()).
                setOptions(Options.newBuilder().setApnsProduction(true).build()).
                setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.alias(phone))
                        .build());

        if (StringUtils.isNotEmpty(extra)) {

            pushPayload.setNotification(Notification.newBuilder().
                    setAlert(content).
                    addPlatformNotification(AndroidNotification.newBuilder().addExtra("data", extra).build()).
                    addPlatformNotification(IosNotification.newBuilder().addExtra("data", extra).build()).build());

        } else {

            pushPayload.setNotification(Notification.alert(content));
        }

        return pushPayload.build();
    }

}
